<?php

namespace App\Models;

use App\Http\Library\WeChat\MiniWeChat;
use Closure;
use Dcat\Admin\Traits\HasDateTimeFormatter;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * App\Models\CashOrder
 *
 * @property int $id
 * @property int $type 0=店铺提现,1=员工提现,2=代理商提现
 * @property string $out_trade_no 提现单号
 * @property int $user_id 用户ID
 * @property int $shop_id 店铺ID
 * @property int $worker_id 员工ID
 * @property int $agent_id 代理商ID
 * @property int $user_bank_id 用户银行卡ID
 * @property array $banks 用户银行卡信息
 * @property string $amount 提现金额
 * @property int $status 审核状态:0=待审核,1=审核通过,2=审核拒绝
 * @property Carbon|null $created_at
 * @property Carbon|null $updated_at
 * @method static Builder|CashOrder newModelQuery()
 * @method static Builder|CashOrder newQuery()
 * @method static Builder|CashOrder query()
 * @method static Builder|CashOrder whereAmount($value)
 * @method static Builder|CashOrder whereCreatedAt($value)
 * @method static Builder|CashOrder whereId($value)
 * @method static Builder|CashOrder whereOutTradeNo($value)
 * @method static Builder|CashOrder whereStatus($value)
 * @method static Builder|CashOrder whereUpdatedAt($value)
 * @method static Builder|CashOrder whereUserId($value)
 * @mixin \Eloquent
 * @property-read \App\Models\User|null $user
 * @method static Builder|CashOrder whereShopId($value)
 * @property-read \App\Models\AgentUser|null $agent
 * @property-read \App\Models\ShopUser|null $shop
 * @property-read \App\Models\Worker|null $worker
 * @method static Builder|CashOrder whereAgentId($value)
 * @method static Builder|CashOrder whereBanks($value)
 * @method static Builder|CashOrder whereType($value)
 * @method static Builder|CashOrder whereUserBankId($value)
 * @method static Builder|CashOrder whereWorkerId($value)
 */
class CashOrder extends Model
{
	use HasDateTimeFormatter;
    protected $table = 'cash_order';

    protected $fillable = [
      'out_trade_no','user_id','shop_id','amount','status','user_bank_id','banks'
    ];

    protected $casts = ['banks'=>'json'];

    protected static function booted()
    {
        self::updating(function (CashOrder $row){
            if ($row->isDirty("status")&&$row->status==1){
                $amount= floatval($row->amount);
                // 处理提现
                if ($row->type==0){
                    ShopUser::moneys(2,$row->shop_id,-$amount,"提现金额");
                }elseif ($row->type==1){
                    Worker::moneys(2,$row->worker_id, -$amount,"提现金额");
                }elseif ($row->type==2){
                    AgentUser::moneys(2,$row->agent_id, -$amount,"提现金额");
                }else{
                    User::amount(2,$row->user_id, -$amount,"提现金额");
                }
//                $wechat = MiniWeChat::instance();
//                $user = $row->user;
//                $openid = $user->openid;
//                $result = $wechat->toBalance($row->out_trade_no,$openid,$amount,"零钱提现");
//                if($result['return_code']==='SUCCESS'&&$result['result_code']==='SUCCESS'){
//                    // 处理提现
//                    if ($row->type==0){
//                        ShopUser::moneys(2,$row->shop_id,-$amount,"提现金额");
//                    }elseif ($row->type==1){
//                        Worker::moneys(2,$row->worker_id, -$amount,"提现金额");
//                    }else{
//                        AgentUser::moneys(2,$row->agent_id, -$amount,"提现金额");
//                    }
//                }else{
//                    if (env("APP_DEBUG")){
//                        Log::error("---------提现失败---------");
//                        Log::error($result);
//                        Log::error("---------提现失败---------");
//                    }
//                    $msg = $result['return_msg']?:'提现失败!';
//                    $msg = $msg=='OK'?$result['err_code_des']:$msg;
//                    modelError($msg);
//                }
            }
        });
    }


    public function user(): HasOne
    {
        return $this->hasOne(User::class,"id","user_id");
    }

    public function shop(): HasOne
    {
        return $this->hasOne(ShopUser::class,"id","shop_id");
    }

    public function worker(): HasOne
    {
        return $this->hasOne(Worker::class,"id","worker_id");
    }

    public function agent(): HasOne
    {
        return $this->hasOne(AgentUser::class,"id","agent_id");
    }

    /**
     * @param $type 0=门店提现,1=员工提现,2=代理商提现
     * @param mixed $model
     * @param $bank_id
     * @return void
     */
    public static function cash($type, mixed $model, $bank_id): void
    {
        $amount = request()->post("amount");
        $amount = $amount?floatval($amount):0;
        DB::beginTransaction();
        $res = false;
        try {
            $banks = UserBank::whereId($bank_id)->where("user_id",$model->user_id)->first();
            if (!$banks){
                throw new \Exception("暂无此银行卡信息");
            }
            $modelData = collect($model)->toArray();
            if (!$modelData){
                throw new \Exception("暂无此账户信息");
            }
            if ($amount<=0){
                throw new \Exception("请输入提现金额");
            }
            $id = $modelData['id'];
            $order = new CashOrder();
            $where = ['status'=>0,"type"=>$type];
            if ($type==0){
                $order->shop_id = $id;
                $where['shop_id'] = $id;
                $where['worker_id'] = 0;
                $where['agent_id'] = 0;
            }elseif ($type==1){
                $order->worker_id = $id;
                $order->shop_id = $modelData['shop_id'];
                $where['worker_id'] = $id;
                $where['shop_id'] = $modelData['shop_id'];
                $where['agent_id'] = 0;
            }elseif ($type==2){
                $order->agent_id = $id;
                $where['agent_id'] = $id;
                $where['shop_id'] = 0;
                $where['worker_id'] = 0;
            }else{
                $where['shop_id'] = 0;
                $where['worker_id'] = 0;
                $where['agent_id'] = 0;
            }
            $cash_money = CashOrder::query()->where($where)->sum("amount");
            if ($type==3){
                $money = floatval($model->amount - $cash_money);
            }else{
                $money = floatval($model->money - $cash_money);
            }
            if ($money<floatval($amount)){
                throw new \Exception("提现金额不可大于可提现金额");
            }
            $order->user_id = $model->user_id;
            $order->amount = $amount;
            $order->type = $type;
            $order->status = 0;
            $order->user_bank_id = $bank_id;
            $order->banks = $banks;
            $order->out_trade_no = build_order_no();
            $res = $order->save();
            DB::commit();
        }catch (\Exception|\PDOException $e){
            DB::rollBack();
            modelError($e->getMessage());
        }
        if ($res){
            modelSuccess("提现申请成功");
        }else{
            modelError("提现申请失败");
        }
    }


    /**
     * 获取用户的收藏列表
     * @param $user_id
     * @return array
     */
    public static function getList($user_id): array
    {
        $type = request()->input('type',0);
        $pageSize = request()->input('pageSize',10);
        $list = self::query()->where("status","<>",2)
            ->where("user_id",$user_id)
            ->where("type",$type)
            ->paginate($pageSize);
//
//        foreach ($list as $item){
//
//        }
        $data['items'] = $list->items();
        $data['lastPage'] = $list->lastPage();
        $data['total'] = $list->total();
        return $data;
    }


}
